﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
// Copyright (C) 2021 kingerrobot
// 版权所有。 
//
// 文件名：BTaskCmd
// 文件功能描述：
//
// 创建者：名字 (zzl)
// 时间：2021/12/6 15:05:46
//
// 修改人：
// 时间：
// 修改说明：
// 版本：V1.0.0
//----------------------------------------------------------------*/
#endregion
namespace KingerRobot.MexicoSailunWMS.SpiService;
internal class BTaskCmd : ITaskCmd
{
    private readonly static ITask _Task = new BTask();


    public List<POWcsTaskCmd> GetTaskCmds()
    {
        var db = Db.Default;
        var result = db.WcsTaskCmds.ToList();
        return result;
    }

    public POWcsTaskCmd GetTaskCmdByTaskId(long taskId)
    {
        var db = Db.Default;
        var result = db.WcsTaskCmds
            .Where(t => t.TaskId == taskId).AsNoTracking()
            .FirstOrDefault();
        return result;
    }

    public POWcsTaskCmd GetTaskCmdByEquipId(long equipId)
    {
        var db = Db.Default;
        var result = db.WcsTaskCmds
            .Where(t => t.EquipId == equipId)
            .FirstOrDefault();
        return result;
    }
    public POWcsTaskCmd GetExecutableTaskCmdByEquipId(long equipId)
    {
        var result = GetTaskCmdByEquipId(equipId);
        if (result == null)
        {
            return null;
        }
        return result.CmdType < (int)EnumTaskCmdStatus.Executed ? result : null;
    }
    public POWcsTaskCmd GetExecutedTaskCmdByEquipId(long equipId)
    {
        var result = GetTaskCmdByEquipId(equipId);
        if (result == null)
        {
            return null;
        }
        return result.CmdType >= (int)EnumTaskCmdStatus.Executed ? result : null;
    }

    public POWcsTaskCmd GetTaskCmdByTaskNo(int taskNo)
    {
        var db = Db.Default;
        var result = db.WcsTaskCmds
            .Where(t => t.TaskNo == taskNo)
            .FirstOrDefault();
        return result;
    }
    public List<POWcsTaskCmd> GetTaskCmdsByGroupNo(int groupNo)
    {
        var db = Db.Default;
        var taskNos = db.WcsTasks.Where(t => t.TaskGroup == groupNo).Select(t => t.TaskNo).ToList();
        if (taskNos.Count == 0)
        { return null; }
        var result = db.WcsTaskCmds
            .Where(t => taskNos.Contains(t.TaskNo))
            .ToList();
        return result;
    }
    public POWcsTaskCmd GetExecutableTaskCmdByTaskNo(int taskNo)
    {
        var result = GetTaskCmdByTaskNo(taskNo);
        return result.CmdStatus < (int)EnumTaskCmdStatus.Executed ? result : null;
    }
    public POWcsTaskCmd GetExecutedTaskCmdByTaskNo(int taskNo)
    {
        var result = GetTaskCmdByTaskNo(taskNo);
        return result?.CmdStatus < (int)EnumTaskCmdStatus.Finish ? result : null;
    }
    public int IsSprayByTaskNo(int taskNo) => GetTaskCmdByTaskNo(taskNo)?.IsSpray ?? 0;



    /// <summary>
    /// 开始位置获取所有任务
    /// </summary>
    /// <param name="locId"></param>
    /// <returns></returns>
    public List<POWcsTaskCmd> GetTaskCmdByStartLocId(long locId)
    {
        var db = Db.Default;
        var result = db.WcsTaskCmds
            .Where(t => t.StartLoc == locId)
            .ToList();
        return result;
    }

    /// <summary>
    /// 结束位置获取所有任务
    /// </summary>
    /// <param name="locId"></param>
    /// <returns></returns>
    public List<POWcsTaskCmd> GetTaskCmdByTargetLocId(long locId)
    {
        var db = Db.Default;
        var result = db.WcsTaskCmds
            .Where(t => t.TargetLoc == locId)
            .ToList();
        return result;
    }

    public POWcsTaskCmd GetNextTaskCmdByLocId(long locId)
    {
        var result = GetTaskCmdByStartLocId(locId).OrderBy(t => t.CreateTime).FirstOrDefault();
        return result;
    }
    //public POWcsTaskCmd GetNextExecutableTaskCmdByLocId(long locId)
    //{
    //    var result = GetTaskCmdByStartLocId(locId);
    //    return result.Where(t => t.CmdStatus < (int)EnumTaskCmdStatus.Executed).OrderBy(t => t.CreateTime).FirstOrDefault();
    //}
    private POWcsTaskCmd GetExecutableTaskCmdByLocId(long locId)
    {
        var result = GetTaskCmdByStartLocId(locId);
        return result.Where(t => t.CmdStatus < (int)EnumTaskCmdStatus.Executed).FirstOrDefault();
    }
    public long GetExecutableTaskCmdIdkByLocId(long locId) => GetExecutableTaskCmdByLocId(locId)?.Id ?? 0;


    private POWcsTaskCmd GetTaskCmdByProductCode(string productCode)
    {
        var task = _Task.GetTaskByProductCode(productCode);
        if (task == null)
        {
            return null;
        }
        return GetTaskCmdByTaskId(task.Id.GetValueOrDefault());
    }
    public long GetTaskCmdIdByProductCode(string productCode) => GetTaskCmdByProductCode(productCode)?.Id ?? 0;



    public POWcsTaskCmd CreateTaskCmd(POWcsTaskCmd pOWcsTaskCmd)
    {
        if (pOWcsTaskCmd.Id.GetValueOrDefault() == 0)
        {
            pOWcsTaskCmd.Id = XID.Nextval;
        }
        if (pOWcsTaskCmd.TaskId == 0
            || pOWcsTaskCmd.StartLoc == 0
            || pOWcsTaskCmd.TargetLoc == 0)
        {
            return null;
        }
        var db = Db.Default;
        db.WcsTaskCmds.Insert(pOWcsTaskCmd);
        return pOWcsTaskCmd;
    }
    public int BakTaskCmdByTaskId(long taskId)
    {

        var taskCmd = GetTaskCmdByTaskId(taskId);
        if (taskCmd is null)
        {
            return 0;
        }
        var db = Db.Default;
        var result = 0;
        try
        {
            result = db.BakWcsTaskCmds.CopyFrom(taskCmd);
        }
        catch (Exception ex)
        {
            //WriteLog(ex.ToString());
        }

        return result;

    }
    public int DeleteTaskCmdByTaskId(long taskId)
    {
        var db = Db.Default;
        var result = db.WcsTaskCmds
            .Where(t => t.TaskId == taskId).Delete();

        return result;
    }
    public int ReSendTaskCmd(List<POWcsTaskCmd> taskCmdList)
    {
        var db = Db.Default;
        var result = 0;
        taskCmdList.ForEach(taskCmd =>
        {
            taskCmd.CmdStatus = (int)EnumTaskCmdStatus.Executable;

            result += db.WcsTaskCmds
              .Where(t => t.Id == taskCmd.Id)
              .Update( new POWcsTaskCmd
              {
                  CmdStatus = (int)EnumTaskCmdStatus.Executable
              });
        }
    );
        return result;
    }
    public int BakAndDeleteCmd(long taskId)
    {
        var db = Db.Default;
        var cmds = db.WcsTaskCmds
            .Where(t => t.TaskId == taskId)
            .ToList();
        var result = 0;
        foreach (var cmd in cmds)
        {
            //if (cmd.CmdStatus < (int)EnumTaskCmdStatus.Executed)
            //{
            //    continue;
            //}
            cmd.FinishMode = (int)EnumFinishMode.ManualEnd;
            db.Update(cmd);
            try { db.BakWcsTaskCmds.CopyFrom(cmd); }
            catch (Exception ex)
            {// WriteLog(ex.ToString());
            };
            result += db.WcsTaskCmds.Where(r => r.Id == cmd.Id).Delete();
        }

        return result;
    }
    public int UpdateTaskCmdStatusForManualEnd(long locId, long taskId, int status)
    {

        var taskCmd = GetTaskCmdByTaskId(taskId);
        if (taskCmd is null)
        {
            return 0;
        }

        long? finishLoc = null;
        int? finishMode = (int)EnumTaskStatus.Create;
        DateTime? finishTime = null;
        // 添加了入库完成验证 lsq
        if (status == (int)EnumTaskStatus.Finish)
        {
            // 完成时修改
            finishLoc = locId;
            finishMode = (int)EnumFinishMode.ManualEnd;
            finishTime = DateTime.Now;
        }

        var db = Db.Default;

        return db.WcsTaskCmds
            .Where(t => t.Id == taskCmd.Id)
            .Update( new POWcsTaskCmd
            {
                CmdStatus = status,
                UpdateTime = DateTime.Now,
                FinishLoc = finishLoc,
                FinishMode = finishMode,
                FinishTime = finishTime
            });
    }
    public int UpdateTaskCmdStatus(long locId, long taskId, int status)
    {

        var taskCmd = GetTaskCmdByTaskId(taskId);
        if (taskCmd is null)
        {
            return 0;
        }

        long? finishLoc = null;
        int? finishMode = (int)EnumTaskStatus.Create;
        DateTime? finishTime = null;
        //添加了入库完成验证 lsq
        if (status == (int)EnumTaskStatus.Finish)
        {
            // 完成时修改
            finishLoc = locId;
            finishMode = (int)EnumFinishMode.NormalEnd;
            finishTime = DateTime.Now;
        }

        var db = Db.Default;

        return db.WcsTaskCmds
            .Where(t => t.Id == taskCmd.Id)
            .Update( new POWcsTaskCmd
            {
                CmdStatus = status,
                UpdateTime = DateTime.Now,
                FinishLoc = finishLoc,
                FinishMode = finishMode,
                FinishTime = finishTime
            });
    }
    public int UpdateTaskCmdStatusByTaskIds(List<long> taskIds, int status)
    {
        long? finishLoc = null;
        int? finishMode = (int)EnumTaskStatus.Create;
        DateTime? finishTime = null;

        var db = Db.Default;

        return db.WcsTaskCmds
            .Where(t => taskIds.Contains(t.TaskId.GetValueOrDefault()))
            .Update( new POWcsTaskCmd
            {
                CmdStatus = status,
                UpdateTime = DateTime.Now,
                FinishLoc = finishLoc,
                FinishMode = finishMode,
                FinishTime = finishTime
            });
    }


    public bool IsTaskCmdByEquipId(long equipId) => GetTaskCmdByEquipId(equipId) is not null;
    public int UpdateTaskCmdPairWait(long equipId, int wait)
    {
        var db = Db.Default;
        var result = db.WcsTaskCmds
            .Where(t => t.EquipId == equipId)
            .Update( new POWcsTaskCmd
            {
                PairWait = wait,
            });

        return result;
    }

    public int UpdateTaskCmdReamrkByTaskId(long taskId, string remark)
    {
        var db = Db.Default;
        var result = 0;
        var data = db.WcsTaskCmds.Where(t => t.TaskId == taskId).FirstOrDefault();
        if (data != null)
        {
            data.RemarkMemo = remark;
            return result;
        }
        return result;
    }

    public List<POWcsTaskCmd> GetTaskCmdsByMasterId(List<long?> masterIds)
    {
        var db = Db.Default;
        var taskIds = db.WcsTasks
            .Where(t => masterIds.Contains(t.MasterId.GetValueOrDefault())).Select(t => t.Id)
            .ToList();
        var result = db.WcsTaskCmds.Where(t => taskIds.Contains(t.Id)).ToList();
        return result;
    }
}